package com.demo.webapp.ui.menu.taglib.el;

import javax.servlet.jsp.JspException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.demo.webapp.ui.menu.taglib.el.MenuTag;
import com.demo.webapp.ui.utils.ExpressionEvaluator;

/**
 * <p>
 * 设置标签所需的HTML hyperlink 'href'属性.
 * 这些属性默认来源于menu-config.xml配置文件.
 * 优先顺序为: 'location', 'page', 'forward';('action'以删除).
 *
 * <p>
 * 在配置文件中设置的&lt;Item&gt;节点中,可以添加属性'location', 'page', 'forward'
 * 'location'属性是优先最高的,将根据PageContext设置Menu的URL地址
 * 'page'属性优先级其次,根据page内容,设置location后,计算Menu的URL地址
 * 'forward'属性的优先级最低,用法与'page'相同,作为备用字段,以后处理。
 * 
 * 以下是一个配置例子:
 * <pre>
 * &lt;Menu name="indexMenuMore" title="More Examples"&gt;
 *   &lt;Item name="actionExample"  title="Example - 'action' attribute"
 *         <B>location="/menu/bullet"</B>/&gt;
 *   &lt;Item name="pageExample" title="Example - 'page' attribute"
 *         <B>page="/bulletmenu.jsp"</B>/&gt;
 * &lt;/Menu&gt;
 * </pre>
 * @author ryuu.kk
 * @version 1.0 $Date: 2012/02/20 at 17:16:39$ 
 */
public class MenuTag extends com.demo.webapp.ui.menu.taglib.MenuTag {
    /**
	 * 版本序列化ID
	 */
	private static final long serialVersionUID = 2591021208844687134L;
	
	//~ Instance fields ========================================================
    protected final static Log log = LogFactory.getLog(MenuTag.class);
    private String name;
    private String target;

    //~ Methods ================================================================
    public void setName(String name) {
        this.name = name;
    }

    public void setTarget(String target) {
        this.target = target;
    }

    public int doStartTag() throws JspException {
    	
    	evaluateExpressions();
    	return super.doStartTag();
    }

    /**
     * 返回page属性
     * 如果page没有设置"/",将page增加一个 "/"
     *
     * @param page page属性
     */
    protected String getPage(String page) {
        if (page.startsWith("/")) {
            return page;
        } else {
            page = "/" + page;
        }

        return page;
    }
    
    public void release() {
        this.name = null;
        this.target = null;
    }
    
	private void evaluateExpressions() throws JspException {
		ExpressionEvaluator eval = new ExpressionEvaluator(this, pageContext);
		if (log.isDebugEnabled()) {
			log.debug(String.format("look at the key [name:%s, target:%s]",	name, target));
		}
		if (name != null) {
			super.setName(eval.evalString("name", name));
		}

		if (target != null) {
			super.setTarget(eval.evalString("target", target));
		}
	}
}
